<template>
  <div class="forum-center">
    <div class="header">
      <h2>论坛中心</h2>
    </div>

    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline class="search-form">
      <el-form-item label="搜索">
        <el-input 
          v-model="searchForm.keyword" 
          placeholder="请输入关键词搜索帖子" 
          clearable 
          style="width: 300px"
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 帖子列表 -->
    <el-table :data="posts" v-loading="loading" border>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="title" label="标题" min-width="250">
        <template #default="{ row }">
          <el-link type="primary" @click="handleView(row)">{{ row.title }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="user_nickname" label="作者" width="120" />
      <el-table-column prop="comments_count" label="评论数" width="80" />
      <el-table-column prop="created_at" label="发布时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.created_at) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 帖子详情对话框 -->
    <el-dialog
      v-model="showDetailModal"
      :title="currentPost?.title"
      width="800px"
      :before-close="handleCloseDetail"
    >
      <div class="post-detail-content" v-if="currentPost">
        <div class="post-meta">
          <span class="author">作者: {{ currentPost.user_nickname }}</span>
          <span class="date">发布时间: {{ formatDateTime(currentPost.created_at) }}</span>
        </div>
        <div class="post-stats">
          <el-tag type="warning">收藏: {{ currentPost.favorites_count }}</el-tag>
          <el-tag type="success">赞: {{ currentPost.likes_count }}</el-tag>
          <el-tag type="danger">踩: {{ currentPost.dislikes_count }}</el-tag>
        </div>
        <div class="post-content" v-html="currentPost.content"></div>
        
        <div class="post-actions">
          <el-button 
            :type="currentPost.is_favorited ? 'warning' : 'default'" 
            :icon="currentPost.is_favorited ? 'StarFilled' : 'Star'"
            @click="toggleCurrentPostFavorite"
          >
            {{ currentPost.is_favorited ? '已收藏' : '收藏' }}
          </el-button>
          <el-button 
            :type="currentPost.like_type === 1 ? 'success' : 'default'" 
            icon="Pointer"
            @click="toggleCurrentPostLike(1)"
          >
            {{ currentPost.like_type === 1 ? '已点赞' : '点赞' }} ({{ currentPost.likes_count }})
          </el-button>
          <el-button 
            :type="currentPost.like_type === -1 ? 'danger' : 'default'" 
            icon="Minus"
            @click="toggleCurrentPostLike(-1)"
          >
            {{ currentPost.like_type === -1 ? '已点踩' : '点踩' }} ({{ currentPost.dislikes_count }})
          </el-button>
        </div>
      </div>
      
      <!-- 评论区域 -->
      <CommentList 
        v-if="currentPost"
        ref="commentListRef"
        :module-id="'post'" 
        :fid="currentPost.id" 
        :show-input="true"
        @comment-submitted="handleCommentSubmitted"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/api/request'
import CommentList from '@/components/CommentList.vue'
import { formatDateTime } from '@/utils'

const loading = ref(false)
const showDetailModal = ref(false)
const commentListRef = ref<any>(null)

const searchForm = reactive({
  keyword: ''
})

const currentPost = ref<any>(null)

const posts = ref<any[]>([])

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取帖子列表
const fetchPosts = async (page = 1) => {
  loading.value = true
  try {
    const params: any = {
      page: page,
      page_size: pagination.size
    }
    
    if (searchForm.keyword) {
      params.search = searchForm.keyword
    }
    
    const response: any = await request.get('/health/public-posts/', { params })
    const postList = response.results || []
    
    // 不再获取每个帖子的状态信息，避免大量并发请求
    posts.value = postList
    pagination.total = response.count || 0
  } catch (error) {
    ElMessage.error('获取帖子列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchPosts()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, { keyword: '' })
  pagination.current = 1
  fetchPosts()
}

// 查看帖子详情
const handleView = async (row: any) => {
  try {
    // 获取帖子详情
    const postResponse: any = await request.get(`/health/posts/${row.id}/`)
    
    // 获取帖子统计信息
    const statsResponse: any = await request.get(`/health/posts/${row.id}/stats/`)
    
    // 获取用户对帖子的状态
    const statusResponse: any = await request.get(`/health/posts/${row.id}/status/`)
    
    currentPost.value = {
      ...postResponse,
      ...statsResponse,
      ...statusResponse
    }
    
    showDetailModal.value = true
  } catch (error) {
    ElMessage.error('获取帖子详情失败')
  }
}

// 关闭详情弹窗
const handleCloseDetail = () => {
  showDetailModal.value = false
  currentPost.value = null
}

// 处理评论提交事件
const handleCommentSubmitted = () => {
  // 评论提交成功后可以做一些处理
  if (commentListRef.value) {
    commentListRef.value.refreshComments()
  }
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  fetchPosts()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchPosts()
}



// 切换当前帖子的收藏状态
const toggleCurrentPostFavorite = async () => {
  if (!currentPost.value) return
  
  try {
    if (currentPost.value.is_favorited) {
      // 取消收藏
      await request.delete(`/health/posts/${currentPost.value.id}/unfavorite/`)
      ElMessage.success('取消收藏成功')
    } else {
      // 收藏
      await request.post(`/health/posts/${currentPost.value.id}/favorite/`)
      ElMessage.success('收藏成功')
    }
    
    // 更新状态
    currentPost.value.is_favorited = !currentPost.value.is_favorited
    
    // 更新统计信息
    if (currentPost.value.is_favorited) {
      currentPost.value.favorites_count += 1
    } else {
      currentPost.value.favorites_count -= 1
    }
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 切换当前帖子的点赞/踩状态
const toggleCurrentPostLike = async (likeType: number) => {
  if (!currentPost.value) return
  
  try {
    // 如果之前已经对该帖子进行了相同操作，则取消操作
    if (currentPost.value.like_type === likeType) {
      // 取消点赞/踩
      await request.delete(`/health/posts/${currentPost.value.id}/unlike/`)
      ElMessage.success('取消操作成功')
      
      // 更新统计信息
      if (likeType === 1) {
        currentPost.value.likes_count -= 1
      } else {
        currentPost.value.dislikes_count -= 1
      }
      
      // 更新状态
      currentPost.value.like_type = null
    } else {
      // 点赞/踩
      await request.post(`/health/posts/${currentPost.value.id}/like/`, { like_type: likeType })
      
      if (likeType === 1) {
        ElMessage.success('点赞成功')
        // 如果之前是点踩状态，需要减少点踩数
        if (currentPost.value.like_type === -1) {
          currentPost.value.dislikes_count -= 1
        }
        currentPost.value.likes_count += 1
      } else {
        ElMessage.success('点踩成功')
        // 如果之前是点赞状态，需要减少点赞数
        if (currentPost.value.like_type === 1) {
          currentPost.value.likes_count -= 1
        }
        currentPost.value.dislikes_count += 1
      }
      
      // 更新状态
      currentPost.value.like_type = likeType
    }
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  }
}

onMounted(() => {
  fetchPosts()
})
</script>

<style scoped>
.forum-center {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.post-detail-content {
  padding: 20px 0;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  color: #666;
}

.post-stats {
  margin: 10px 0;
  display: flex;
  gap: 10px;
}

.post-actions {
  margin: 15px 0;
  display: flex;
  gap: 10px;
}

.post-content {
  line-height: 1.8;
}

.post-content :deep(img) {
  max-width: 100%;
  height: auto;
}
</style>